package com.sl.au.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sl.au.entity.Account;
import com.sl.au.entity.Chance;
import com.sl.au.entity.ChanceDelivery;
import com.sl.au.entity.ChanceDeliveryTemp;
import com.sl.au.entity.JPushMsg;
import com.sl.au.entity.Module;
import com.sl.au.entity.Option;
import com.sl.au.entity.SaleArea;
import com.sl.au.entity.Section;
import com.sl.au.entity.SectionArea;
import com.sl.au.entity.User;
import com.sl.au.service.ChanceDeliveryService;
import com.sl.au.service.ChanceFlowNodeService;
import com.sl.au.service.ChanceService;
import com.sl.au.service.ExdeviExdePersonRoleInfoService;
import com.sl.au.service.JGPushService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.SectionService;
import com.sl.au.service.UserService;
import com.sl.utils.ExdeUtil;

@RestController
@RequestMapping(value = "/ui/chanceDelivery")
public class ChanceDeliveryController extends BaseController {

	@Autowired
	ChanceDeliveryService chanceDeliveryService;

	@Autowired
	SaleAreaService saleAreaService;

	@Autowired
	OptionService optionService;

	@Autowired
	UserService userService;

	@Autowired
	ChanceService chanceService;

	@Autowired
	OperateLogService operateLogService;
	
	@Autowired
	ChanceFlowNodeService chanceFlowNodeService;

	@Autowired
	SectionService sectionService;
	
	@Autowired
	JGPushService jPushService;

	@Autowired
	ExdeviExdePersonRoleInfoService exdeviExdePersonRoleInfoService;
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		ModelAndView modelAndView = this.createLayoutView("chanceDelivery/chanceDeliveryindex");
		String group = "上级部门";
		Account a = this.getMyAccount();
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		List<Option> superiors = new ArrayList<Option>();
		List<SaleArea> saleAreas = new ArrayList<SaleArea>();
		superiors = optionService.getRepository().findByGroup(group);
		saleAreas = saleAreaService.getRepository().getAllSaleArea();
		modelAndView.addObject("saleAreas", saleAreas);
		modelAndView.addObject("superiors", superiors);
		modelAndView.addObject("userSuperior", userSuperior);
		return modelAndView;
	}

	/**
	 * 销售信息服务器分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage1", method = RequestMethod.GET)
	public Map<String, Object> getPage1(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if(key==null) key="";
		String isReceived = request.getParameter("state");
		String aa = request.getParameter("targetType");
		int targetType = Integer.parseInt(request.getParameter("targetType"));
		//int targetType=Integer.valueOf(request.getParameter("targetType")).intValue();
		//String targetType = request.getParameter("targetType");
		/*if(isReceived.equals("传递")){
			targetType = "2";
		}else if(isReceived.equals("本部")){
			targetType = "0";
		}else if(isReceived.equals("协作")){
			targetType = "1";
		}*/
		Module module = this.getPageModule("chanceDelivery");
		String dataFilter=module.getDataFilter();
		Account a = this.getMyAccount();
		String sectionId=null;
		String userSuperior =null;
		String userId=null;
		Long count;
		if(a!=null){
			User chief=a.getUser();
			userId=chief.getId();
			userSuperior = chief.getSaleArea().getSuperior();
			Section section=sectionService.getRepository().findByChief(chief);
			if(section!=null){
				sectionId=section.getId();
			}
			
		}
		condition.put("key", key);
		condition.put("userSuperior", userSuperior);
		condition.put("isReceived", isReceived);
		condition.put("sectionId", sectionId);
		condition.put("dataFilter", dataFilter);
		condition.put("userId", userId);
		
		List<Chance> saleChances = chanceDeliveryService.getPage(start, length, condition,targetType, null, null);
		if(dataFilter.equals("本科室")){
			if(targetType == 4){
				count=chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived, sectionId);
			}else{				
				count=chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived, sectionId,targetType);
			}
		}else{
			if(targetType == 4){
				count = chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived);
			}else{				
				count = chanceDeliveryService.getRepository().getAllChanceCountOne(userSuperior, key, isReceived,targetType);
			}
		}
			//count = chanceDeliveryService.getRepository().getAllChanceCountOne(userSuperior, key, isReceived,targetType);
			//count = chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 销售信息服务器分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if(key==null) key="";
		String isReceived = request.getParameter("state");
		Module module = this.getPageModule("chanceDelivery");
		String dataFilter=module.getDataFilter();
		Account a = this.getMyAccount();
		String sectionId=null;
		String userSuperior =null;
		String userId=null;
		Long count;
		if(a!=null){
			User chief=a.getUser();
			userId=chief.getId();
			userSuperior = chief.getSaleArea().getSuperior();
			Section section=sectionService.getRepository().findByChief(chief);
			if(section!=null){
				sectionId=section.getId();
			}
			
		}
		condition.put("key", key);
		condition.put("userSuperior", userSuperior);
		condition.put("isReceived", isReceived);
		condition.put("sectionId", sectionId);
		condition.put("dataFilter", dataFilter);
		condition.put("userId", userId);
		
		List<Chance> saleChances = chanceDeliveryService.getPage(start, length, condition, null, null);
		if(dataFilter.equals("本科室")){
				count=chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived, sectionId);
		}else{
				count = chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived);
		}
			//count = chanceDeliveryService.getRepository().getAllChanceCountOne(userSuperior, key, isReceived,targetType);
			//count = chanceDeliveryService.getRepository().getAllChanceCount(userSuperior, key, isReceived);
		map.put("data", saleChances);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 信息片区分配弹窗保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/deliverysave", method = RequestMethod.POST)
	public Map<String, Object> saveSaleChance(HttpServletRequest request, @RequestBody ChanceDelivery chanceDelivery) {
		Map<String, Object> map = new HashMap<String, Object>();
		chanceDeliveryService.getRepository().save(chanceDelivery);
		// 保存日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		Chance saleChance = chanceService.getRepository().findOne(chanceDelivery.getSaleChance().getId());
		SaleArea saleArea = saleAreaService.getRepository().findOne(chanceDelivery.getSaleArea().getId());
		String chanceName = saleChance.getName();
		String araeName = saleArea.getSuperiorArea();
		
		String superior = saleArea.getSuperior();
		String areaName1 = saleArea.getAreaName();
		List<String> list = new ArrayList<>();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("片区经理", superior, areaName1);
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("片区经理"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "分配到" + superior + areaName1);
		msg.setTitle("信息" + chanceName);
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "分配销售信息【" + chanceName + "】到【" + araeName + "】";
		operateLogService.log(user, "信息分配片区", content);
		//写入信息流转
		Chance chance = new Chance();
		chance.setId(chanceDelivery.getSaleChance().getId());
		chanceFlowNodeService.flow(user, chance, user.getEmpLogin().getUserName(), araeName, "信息分配片区");
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
	/**
	 * 信息片区分配弹窗保存(mobile)
	 * 一次保存多条区域分配
	 * @return
	 */
	@RequestMapping(value = "/deliverysave/mobile", method = RequestMethod.POST)
	public Map<String, Object> saveSaleChanceMobile(HttpServletRequest request,@RequestBody Map<String,Object> data) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceId=data.get("chanceId").toString();
		String chanceTempId=data.get("chanceTempId").toString();
		map.put("code", -1);
		if(!StringUtils.hasText(chanceId)) return map;		
		Chance chance=chanceService.getRepository().findOne(chanceId);
		if(null==chance) return map;
		int targetType=0;
		//移动端更新信息接收状态
		if(chanceTempId!=null){
			ChanceDeliveryTemp deliveryTemp=chanceDeliveryService.getDeliveryTempRepository().findOne(chanceTempId);
			if(1==deliveryTemp.getChanceType())
				targetType=1;
			if(deliveryTemp.getIsReceived()!=1){
			      deliveryTemp.setIsReceived(1);
			      chanceDeliveryService.getDeliveryTempRepository().save(deliveryTemp);
			}
		}
		Account a = this.getMyAccount();
		User user = a.getUser();
		@SuppressWarnings("unchecked")
		List<String> ids=(List<String>) data.get("ids");
		List<ChanceDelivery> list=new ArrayList<>();
		ChanceDelivery delivery=null;SaleArea area=null;
		for(String id:ids){
			if(!StringUtils.hasText(id)) continue;
			delivery=new ChanceDelivery();
			delivery.setIsReceived(0);
			delivery.setTargetType(targetType);
			area=saleAreaService.getRepository().findOne(id);
			delivery.setSaleArea(area);
			delivery.setSaleChance(chance);
			list.add(delivery);
		}
		this.chanceDeliveryService.getRepository().save(list);
		for(ChanceDelivery d:list){
			chanceFlowNodeService.flow(user, d.getSaleChance(),
					user.getEmpLogin().getUserName(), d.getSaleArea().getSuperiorArea(), "信息分配片区");
			String content = "分配销售信息【" + chance.getName() + "】到【" + d.getSaleArea().getSuperiorArea() + "】";
			operateLogService.log(user, "信息分配片区", content);
		}
		for(ChanceDelivery d:list){
			List<String> lists = new ArrayList<>();
			List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("片区经理", d.getSaleArea().getSuperior(), d.getSaleArea().getAreaName());
			for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
				lists.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
			}
			System.out.println("片区经理"+exdeviExdePersonRoleInfos.size());
			JPushMsg msg = new JPushMsg();
			msg.setAlias(lists);
			msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + d.getSaleChance().getName() + "分配到" + d.getSaleArea().getSuperior() + d.getSaleArea().getAreaName());
			msg.setTitle("信息" + d.getSaleChance().getName());
			Map<String, String> extras = new HashMap<>();
			extras.put("ex1", "附加内容1");
			extras.put("ex2", "附加内容2");
			jPushService.sendClient(msg, extras);
		}
		
		map.put("code", 0);
		return map;
	}
	/**
	 * 信息片区分配弹窗分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getModulePage", method = RequestMethod.GET)
	public Map<String, Object> getModulePage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String Type = request.getParameter("targetType");
		Account a = this.getMyAccount();
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		int targetType = 0;
		if (Type != null) {
			if (Type.equals("1")) {
				targetType = 1;
			}
		}
		String chanceId = request.getParameter("chanceId");
		List<ChanceDelivery> saleAreas = null;
		condition.put("chanceId", chanceId);
		condition.put("targetType", targetType);
		condition.put("userSuperior", userSuperior);
		saleAreas = chanceDeliveryService.getModulePage(start, length, condition, null, null);
		Long count = chanceDeliveryService.getRepository().getModuleAreaCount(chanceId, targetType, userSuperior);

		map.put("data", saleAreas);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 信息发起协作弹窗保存
	 * 
	 * @return
	 */
	@RequestMapping(value = "/cooperationsave", method = RequestMethod.POST)
	public Map<String, Object> saveCoopSaleChance(HttpServletRequest request,
			@RequestBody ChanceDeliveryTemp chanceDeliveryTemp) {
		Map<String, Object> map = new HashMap<String, Object>();
		chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
		// 保存日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		Chance saleChance = chanceService.getRepository().findOne(chanceDeliveryTemp.getSaleChance().getId());
		String chanceName = saleChance.getName();
		String superior = chanceDeliveryTemp.getReceiveSuperior();
		
		//String superior = saleArea.getSuperior();
		//String areaName1 = saleArea.getAreaName();
		List<String> list = new ArrayList<>();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("处长", superior);
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("处长"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "协作到" + superior);
		msg.setTitle("信息" + chanceName);
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "销售信息【" + chanceName + "】向【" + superior + "】发起协作";
		operateLogService.log(user, "信息分配片区", content);
		//写入流转记录
		Chance chance = new Chance();
		chance.setId(chanceDeliveryTemp.getSaleChance().getId());
		chanceFlowNodeService.flow(user, chance,user.getEmpLogin().getUserName(), superior,"发起协作");
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
	/**
	 * 信息发起协作弹窗保存(mobile)正在用
	 * 
	 * @return
	 */
	@RequestMapping(value = "/cooperationsaveMobile", method = RequestMethod.POST)
	public Map<String, Object> mobileSaveCoopSaleChance(HttpServletRequest request,
			@RequestBody ChanceDeliveryTemp chanceDeliveryTemp) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceTempId=request.getParameter("chanceTempId");
		map.put("code",-1);
		if(chanceTempId==null) return map;
		//移动端更新信息接收状态
		ChanceDeliveryTemp deliveryTemp=chanceDeliveryService.getDeliveryTempRepository().findOne(chanceTempId);
		if(deliveryTemp==null) return map;
		if(deliveryTemp.getIsReceived()!=1){
			deliveryTemp.setIsReceived(1);
			chanceDeliveryService.getDeliveryTempRepository().save(deliveryTemp);
		}
		chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
		// 保存日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		Chance saleChance = chanceService.getRepository().findOne(chanceDeliveryTemp.getSaleChance().getId());
		String chanceName = saleChance.getName();
		String superior = chanceDeliveryTemp.getReceiveSuperior();
		
		List<String> list = new ArrayList<>();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("处长", superior);
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("处长"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "协作到" + superior);
		msg.setTitle("信息" + chanceName);
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		
		String content = "销售信息【" + chanceName + "】向【" + superior + "】发起协作";
		operateLogService.log(user, "信息分配片区", content);
		//写入流转记录
		Chance chance = new Chance();
		chance.setId(chanceDeliveryTemp.getSaleChance().getId());
		chanceFlowNodeService.flow(user, chance,user.getEmpLogin().getUserName(), superior,"发起协作");
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
	/**
	 * 信息发起协作弹窗保存，mobile 多个协作(弃用)
	 * 
	 * @return
	 */
	@RequestMapping(value = "/cooperationsave/mobile", method = RequestMethod.POST)
	public Map<String, Object> saveCoopSaleChanceMobile(HttpServletRequest request,
			@RequestBody Map<String,Object> params) {
		@SuppressWarnings("unchecked")
		List<ChanceDeliveryTemp> temps=(List<ChanceDeliveryTemp>)params.get("temps");
		Map<String, Object> map = new HashMap<String, Object>();
		ObjectMapper mapper=new ObjectMapper();		
		map.put("code", -1);
		for(ChanceDeliveryTemp chanceDeliveryTemp:temps){
			chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
			// 保存日志
			Account a = this.getMyAccount();
			User user = a.getUser();
			Chance saleChance = chanceService.getRepository().findOne(chanceDeliveryTemp.getSaleChance().getId());
			String chanceName = saleChance.getName();
			String superior = chanceDeliveryTemp.getReceiveSuperior();
			String content = "销售信息【" + chanceName + "】向【" + superior + "】发起协作";
			operateLogService.log(user, "信息分配片区", content);
			//写入流转记录
			Chance chance = new Chance();
			chance.setId(chanceDeliveryTemp.getSaleChance().getId());
			chanceFlowNodeService.flow(user, chance,user.getEmpLogin().getUserName(), superior,"发起协作");
		}
	
		map.put("code", 0);
		return map;
	}

	/**
	 * 信息发起协作弹窗分页数据
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/getModulePageCoop", method = RequestMethod.GET)
	public Map<String, Object> getModulePageCoop(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String chanceId = request.getParameter("chanceId");
		List<ChanceDeliveryTemp> chanceDeliveryTemps = null;

		chanceDeliveryTemps = chanceDeliveryService.getModulePageCoop(start, length, chanceId, null, null);
		Long count = chanceDeliveryService.getRepository().getModuleAreaCoopCount(chanceId);

		map.put("data", chanceDeliveryTemps);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 验证是否分配选中片区
	 * 
	 * @return
	 */
	@RequestMapping(value = "/validArea", method = RequestMethod.GET)
	public Map<String, Object> validArea(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String areaId = request.getParameter("areaId");
		String chanceId = request.getParameter("chanceId");
		ChanceDelivery chanceDelivery = chanceDeliveryService.getRepository().validArea(areaId, chanceId);
		int isDelivery = 0;
		if (chanceDelivery != null) {
			isDelivery = 1;
		}
		map.put("isDelivery", isDelivery);
		return map;
	}

	// 删除片区
	@RequestMapping(value = "/deleteArea", method = RequestMethod.GET)
	public Map<String, Object> delBid(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<ChanceDelivery> chanceDeliverys = new ArrayList<ChanceDelivery>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		String saleChance = "";

		for (int i = 0; i < id.length; i++) {
			String deliveryId = id[i];
			ChanceDelivery chanceDelivery = new ChanceDelivery();
			chanceDelivery.setId(deliveryId);
			chanceDeliverys.add(chanceDelivery);
			saleChance = chanceDelivery.getSaleChance().getId();
			// 保存日志
			ChanceDelivery chanceDdelivery = chanceDeliveryService.getRepository().findOne(deliveryId);
			Chance chance = chanceDdelivery.getSaleChance();
			String chanceName = chanceDdelivery.getSaleChance().getName();
			String superior = chanceDdelivery.getSaleArea().getSuperiorArea();
			String content = "销售信息【" + chanceName + "】撤回分配片区【" + superior + "】";
			operateLogService.log(user, "信息分配片区", content);
			//写入流转记录
			chanceFlowNodeService.flow(user, chance, user.getEmpLogin().getUserName(), "撤回"+superior, "撤回分配片区");
		}
		chanceDeliveryService.getRepository().deleteInBatch(chanceDeliverys);
		List<String> newchanceDeliverys = chanceDeliveryService.getRepository().getDistributedSaleAreas(saleChance);
		if(newchanceDeliverys == null){
			ChanceDeliveryTemp ChanceDeliveryTemp = chanceDeliveryService.getRepository().findBysaleChance(saleChance);
			ChanceDeliveryTemp.setIsReceived(0);
			chanceDeliveryService.getDeliveryTempRepository().save(ChanceDeliveryTemp);
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 验证是否可以传递部门
	 * 
	 * @return
	 */
	@RequestMapping(value = "/validSuperior", method = RequestMethod.GET)
	public Map<String, Object> validSuperior(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceId = request.getParameter("chanceId");
		// num为0说明可以传递部门
		int num = chanceDeliveryService.getRepository().validSuperior(chanceId);
		map.put("num", num);
		return map;
	}
	
	/**
	 * 移动端传递部门
	 * 
	 * @return
	 */
	@RequestMapping(value = "/transmitSuperior", method = RequestMethod.POST)
	public Map<String, Object> transmitSuperior(HttpServletRequest request,
			@RequestBody ChanceDeliveryTemp chanceDeliveryTemp) {
		Map<String, Object> map = new HashMap<String, Object>();
		chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
		Account a = this.getMyAccount();
		User user = a.getUser();
		//日志
		String content = "传递销售信息【"+chanceDeliveryTemp.getSaleChance().getName()+"】到【"+chanceDeliveryTemp.getReceiveSuperior()+"】";
		operateLogService.log(user, "信息传递部门", content);
		//写入流转记录
		chanceFlowNodeService.flow(user,chanceDeliveryTemp.getSaleChance(), user.getName(),chanceDeliveryTemp.getReceiveSuperior(),"信息传递");
		map.put("code", 0);
		return map;
	}

	/**
	 * 验证是否对选中部门发起协作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/validCoopSuperior", method = RequestMethod.GET)
	public Map<String, Object> validCoopSuperior(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String chanceId = request.getParameter("chanceId");
		String superior = request.getParameter("coopSuperior");
		ChanceDeliveryTemp chanceDeliveryTemp = chanceDeliveryService.getRepository().validCoopSuperior(chanceId,
				superior);
		int isDelivery = 0;
		if (chanceDeliveryTemp != null) {
			isDelivery = 1;
		}
		map.put("isDelivery", isDelivery);
		return map;
	}

	// 删除协作部门
	@RequestMapping(value = "/deleteCoop", method = RequestMethod.GET)
	public Map<String, Object> deleteCoop(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		String id[] = ids.split(",");
		List<ChanceDeliveryTemp> chanceDeliveryTemps = new ArrayList<ChanceDeliveryTemp>();
		// 保存日志
		Account a = this.getMyAccount();
		User user = a.getUser();
		for (int i = 0; i < id.length; i++) {
			String tempId = id[i];
			ChanceDeliveryTemp chanceDeliveryTemp = new ChanceDeliveryTemp();
			chanceDeliveryTemp.setId(tempId);
			chanceDeliveryTemps.add(chanceDeliveryTemp);
			ChanceDeliveryTemp chanceDdeliveryTemp = chanceDeliveryService.getDeliveryTempRepository().findOne(tempId);
			Chance chance = chanceDdeliveryTemp.getSaleChance();
			String chanceName = chanceDdeliveryTemp.getSaleChance().getName();
			String superior = chanceDdeliveryTemp.getReceiveSuperior();
			String content = "销售信息【" + chanceName + "】撤回协作部门【" + superior + "】";
			operateLogService.log(user, "信息分配片区", content);
			//写入流转记录
			chanceFlowNodeService.flow(user, chance, user.getEmpLogin().getUserName(), superior+"撤回", "撤回协作部门");
		}
		chanceDeliveryService.getDeliveryTempRepository().deleteInBatch(chanceDeliveryTemps);
		map.put("code", 0);
		return map;
	}

	/**
	 * 机会分配页面（片区经理）
	 * 
	 * @return
	 */
	@RequestMapping(value = "managerDelivery")
	public ModelAndView managerDelivery() {
		ModelAndView modelAndView = this.createLayoutView("chanceDelivery/managerDelivery");
		Account a = this.getMyAccount();
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		String userId = a.getUser().getId();
		String areaId = a.getUser().getSaleArea().getId();
		List<User> users = userService.getRepository().findAll();
		modelAndView.addObject("users", users);
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("areaId", areaId);
		modelAndView.addObject("userSuperior", userSuperior);
		return modelAndView;
	}
	@RequestMapping(value="/saleareas/{chanceId}",method=RequestMethod.GET)
	public Map<String,Object> getChanceDeliveryDistributed(@PathVariable String chanceId){
		Map<String,Object> map=new HashMap<String,Object>();
		String superior=this.getMyAccount().getUser().getSaleArea().getSuperior();
		map.put("code",-1);
		List<String> selectedIds=chanceDeliveryService.getRepository().getDistributedSaleAreas(chanceId);
		List<SaleArea> saleAreas=saleAreaService.getRepository().findBySuperior(superior);
		if(null!=saleAreas){
			for(SaleArea a:saleAreas){
				a.setIsSelected(false);
			}
		}
		map.put("selectedIds", selectedIds);
		map.put("saleAreas", saleAreas);
		map.put("code", 0);
		return map;
	}
	/**得到协作界面的数据
	 * @return
	 */
	@RequestMapping(value="/cooperate-data/{chanceId}",method=RequestMethod.GET)
	public Map<String,Object> getChanceCooperateData(@PathVariable String chanceId){
		Map<String,Object> map=new HashMap<String,Object>();		
		map.put("code",-1);
		
		String group = "上级部门";
		Account a = this.getMyAccount();
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		List<Option> superiors = new ArrayList<Option>();
		superiors = optionService.getRepository().findByGroup(group).stream()
				.filter(t->t.getTitle().equals("销售处")||t.getTitle().equals("成套处")||t.getTitle().equals("外贸处"))
				.collect(Collectors.toList());
		List<String> cooperatedSuperiors=chanceDeliveryService.getRepository().findCooperatedSuperiors(chanceId);
		cooperatedSuperiors.add(userSuperior);
		map.put("superiors", superiors);
		map.put("cooperatedSuperiors", cooperatedSuperiors);
		map.put("code", 0);
		return map;
	}
	/**得到传递部门界面的数据
	 * @return
	 */
	@RequestMapping(value="/transmit-data/{chanceId}",method=RequestMethod.GET)
	public Map<String,Object> getChanceTransmitData(@PathVariable String chanceId){
		Map<String,Object> map=new HashMap<String,Object>();		
		map.put("code",-1);
		
		String group = "上级部门";
		Account a = this.getMyAccount();
		String userSuperior = a.getUser().getSaleArea().getSuperior();
		List<Option> superiors = new ArrayList<Option>();
		superiors = optionService.getRepository().findByGroup(group).stream()
				.filter(t->t.getTitle().equals("销售处")||t.getTitle().equals("成套处")||t.getTitle().equals("外贸处"))
				.collect(Collectors.toList());
		List<String> cooperatedSuperiors=new ArrayList<>();
		cooperatedSuperiors.add(userSuperior);
		map.put("superiors", superiors);
		map.put("cooperatedSuperiors", cooperatedSuperiors);
		map.put("code", 0);
		return map;
	}
	/**关闭一个机会
	 * @param chanceId
	 * @return
	 */
	@RequestMapping(value="/close",method=RequestMethod.POST)
	public Map<String,Object> closeChance(@RequestBody Map<String,Object>params){
		Map<String,Object> map=new HashMap<String,Object>();		
		map.put("code",-1);

		 String chanceId=params.get("chanceId").toString();
		 String reason=params.get("reason").toString();
		 String contractCode=params.get("contractCode").toString();
		 String result=params.get("result").toString();
		 String chanceTempId=params.get("chanceTempId").toString();
		 
		 if(!StringUtils.hasText(chanceId)) return map;
		
		this.chanceDeliveryService.closeChance(this.getMyAccount().getUser(),chanceId,reason, contractCode, result);
		ChanceDeliveryTemp chanceDeliveryTemp= this.chanceDeliveryService.getDeliveryTempRepository().findOne(chanceTempId);
		if(chanceDeliveryTemp.getIsReceived()!=1){
			chanceDeliveryTemp.setIsReceived(1);
			this.chanceDeliveryService.getDeliveryTempRepository().save(chanceDeliveryTemp);
		}
		
		
		map.put("code", 0);
		return map;
	}
	
	/**
	 * @param chanceId
	 * @return
	 */
	@RequestMapping(value="/saveChanceDeliveryTemps",method=RequestMethod.POST)
	public Map<String,Object> saveChanceDeliveryTemps(HttpServletRequest request){
		Map<String,Object> map=new HashMap<String,Object>();
		ChanceDeliveryTemp chanceDelivery = chanceDeliveryService.getDeliveryTempRepository().findOne(request.getParameter("id"));
		Account a = this.getMyAccount();
		User user = a.getUser();
		List<String> list = new ArrayList<>();
		String superior = chanceDelivery.getReceiveSuperior();
		String chanceName = chanceDelivery.getSaleChance().getName();
		List<String> exdeviExdePersonRoleInfos = exdeviExdePersonRoleInfoService.findRoles("处长", superior);
		for(String exdeviExdePersonRoleInfo : exdeviExdePersonRoleInfos){
			list.add(ExdeUtil.splitString(exdeviExdePersonRoleInfo));
		}
		System.out.println("处长"+exdeviExdePersonRoleInfos.size());
		JPushMsg msg = new JPushMsg();
		msg.setAlias(list);
		msg.setContent("信息待处理：" + user.getName() + "将销售信息：" + chanceName + "协作到" + superior);
		msg.setTitle("信息" + chanceName);
		Map<String, String> extras = new HashMap<>();
		extras.put("ex1", "附加内容1");
		extras.put("ex2", "附加内容2");
		jPushService.sendClient(msg, extras);
		map.put("code", 0);
		return map;
	}
}
